<?php

class Firma {
	
	public $id_firma;
	public $id_client;
	public $nume;
	public $cf;
	public $rc;
	public $tel_fix;
	public $tel_fax;
	public $tel_mobil;
	public $email;
	public $web;
	public $tip;
	public $version;
	public $adresa;
	public $conturi;
	public $contacte;
	public $rute;
	
	public $comentariu;
	public $calitate_firma;
	
	public function __construct($id_client=null, $nume = null, $cf=null, $rc=null, $tel_fix=null, $tel_fax=null, $tel_mobil=null, $email=null
								, $web=null, $tip=null) {
		$this->id_client = $id_client;
		$this->nume = $nume;
		$this->cf = $cf;
		$this->rc = $rc;
		$this->tel_fix = $tel_fix;
		$this->tel_mobil = $tel_mobil;
		$this->tel_fax = $tel_fax;
		$this->email = $email;
		$this->web = $web;
		$this->tip = $tip;
		$this->version = 0;
		$this->id_firma = CT_NOT_SAVED_YET;
		
		$this->adresa = new Address(CT_ADRESA_FIRMA, '', '', '', '', '', '', '', '');
		$this->conturi = array();
		$this->contacte = array();
		$this->rute = array();
	}
	
	public function queryInsert($db) {
		
		$query = $db->prepare("INSERT INTO `firme`  (	`id_client` , 			`nume` , 
														`cf` , 					`rc`,
                        		        				`tel_fix` ,    			`tel_mobil` , 
	                        	        				`tel_fax` , 		    `email` , 
	                                					`web` ,					`tip`,
	                                					`version`,				`comentariu`,
	                                					`calitate_firma` 		                              
	                               					) 
	            						VALUES  	(	:id_client,     		:nume, 
	            										:cf,   					:rc, 
	                      								:tel_fix,    			:tel_mobil, 
	                      								:tel_fax,     			:email,
	                      								:web,   				:tip,
	                      								:version,				:comentariu,
	                      								:calitate_firma		                      				
	                      							);");
		
		
		$query->bindParam(':id_client', ($this->id_client));
		$query->bindParam(':nume', 		($this->nume));
		$query->bindParam(':cf', 		($this->cf));
		$query->bindParam(':rc', 		($this->rc));
		$query->bindParam(':tel_fix', 	($this->tel_fix));
		$query->bindParam(':tel_mobil', ($this->tel_mobil));
		$query->bindParam(':tel_fax', 	($this->tel_fax));
		$query->bindParam(':email', 	($this->email));
		$query->bindParam(':web', 		($this->web));
		$query->bindParam(':tip', 		($this->tip));
		$query->bindParam(':version', 	($this->version));
		$query->bindParam(':comentariu', 	($this->comentariu));
		$query->bindParam(':calitate_firma', 	($this->calitate_firma));
					
		try {  		
			$db->beginTransaction();

			if ($query->execute() === FALSE) {	
			
                $errInfo = $query->errorInfo();
                $errInfo = $errInfo[2];
            	$query->closeCursor();

				throw new QueryInsertFirmaException("Failed saving firma to the database" . $errInfo);		
			}
			
  			$this->id_firma = (int) $db->lastInsertId();
  			$query->closeCursor();
  			//inserarea adresei
  			$this->adresa->id_owner = $this->id_firma;
  			$adresa_ok = $this->adresa->queryInsertAddress($db);
  			//end inserarea adresei
			
  			//inserare contacte		 		
	  		for ($i = 0; $i < count($this->contacte); $i++) {

	  			//completam campul de id_owner la conturi pentru ca la creearea de firma noua acest camp nu se stie pana cand
	  			//nu se face insertul proproiuzis cu datele firmei
	  			if ($this->contacte[$i]->status != CT_CONTACT_DELETED) {
		  			$this->contacte[$i]->id_firma = $this->id_firma;		  			
		  			$this->contacte[$i]->queryInsertContact($db);	  		
	  			}	
	  		}
	  		
  			//inserarea conturilor
	  		for ($i = 0; $i < count($this->conturi); $i++) {
	  			//completam campul de id_owner la conturi pentru ca la creearea de firma noua acest camp nu se stie pana cand
	  			//nu se face insertul proproiuzis cu datele firmei
	  			if ($this->conturi[$i]->status != CT_CONT_DELETED) {
		  			$this->conturi[$i]->id_owner = $this->id_firma;
		  			$this->conturi[$i]->queryInsertCont($db);	 		
	  			}	
	  		}	  		
  			//end inserarea conturilor

	  		//urmeaza acuma inserarea rutelor
			for ($i = 0; $i < count($this->rute); $i++) {
	  			//completam campul de id_owner la conturi pentru ca la creearea de firma noua acest camp nu se stie pana cand
	  			//nu se face insertul proproiuzis cu datele firmei
	  			if ($this->rute[$i]->status != CT_RUTA_FIRMA_DELETED) {
		  			$this->rute[$i]->firma_id = $this->id_firma;
		  			$this->rute[$i]->queryInsertRutaFirma($db);	 			
	  			}
	  		}	  		
  			$db->commit();
		}
		catch (QueryInsertFirmaException $e) {
			$db->rollBack();	//maybe NOT needed ????
			$query->closeCursor();
			throw new QueryInsertFirmaException("Failed saving firma to the database" . $errInfo);
		}
		catch (QueryInsertAddressException $e) {
			$db->rollBack();	
			$query->closeCursor();
			throw new QueryInsertFirmaException("Failed saving firma to the database! reason: addres" . $errInfo);
		}
		catch (QueryInsertContException $e) {
			$db->rollBack();	
			$query->closeCursor();
			throw new QueryInsertFirmaException("Failed saving firma to the database! reason: cont" . $errInfo);
		}		
		catch (QueryInsertContactException $e) {
			$db->rollBack();	
			$query->closeCursor();
			throw new QueryInsertFirmaException("Failed saving firma to the database! reason: contact" . $errInfo);
		}	
		catch (QueryInsertRutaFirmaException $e) {
			$db->rollBack();	
			$query->closeCursor();
			throw new QueryInsertFirmaException("Failed saving firma to the database! reason: rute" . $errInfo);			
		}
			  			       
		return $this->id_firma; 		
	}
	
	public function queryUpdate($db) {			    	      
		$this->version++;

		$query = $db->prepare("UPDATE `firme` SET      	    `id_client` = :id_client , 		`nume` = :nume, 
															`cf` = :cf , 					`rc` = :rc,
	                        		        				`tel_fix` = :tel_fix,    		`tel_mobil` = :tel_mobil, 
		                        	        				`tel_fax` = :tel_fax, 			`email` = :email, 
		                                					`web` = :web, 					`tip` = :tip,
		                                					`version` = :version,			`comentariu` = :comentariu,
		                                					`calitate_firma` = :calitate_firma
               	  					WHERE version < :version 
               	  						AND id = :id_firma
               	  						AND id_client = :id_client");

		
		$query->bindParam(':id_client', ($this->id_client));	
		$query->bindParam(':nume', 		($this->nume));	
		$query->bindParam(':cf', 		($this->cf));	
		$query->bindParam(':rc', 		($this->rc));	
		$query->bindParam(':tel_fix', 	($this->tel_fix));	
		$query->bindParam(':tel_mobil', ($this->tel_mobil));	
		$query->bindParam(':tel_fax', 	($this->tel_fax));	
		$query->bindParam(':email', 	($this->email));	
		$query->bindParam(':web', 		($this->web));	
		$query->bindParam(':tip', 		 $this->tip);	
		$query->bindParam(':version', 	($this->version));	
		$query->bindParam(':id_firma', 	($this->id_firma));	
		$query->bindParam(':comentariu', 	($this->comentariu));		
		$query->bindParam(':calitate_firma', 	($this->calitate_firma));		

		try {  		
			$db->beginTransaction();
			
			if ($query->execute() === FALSE) {			
                $errInfo = $query->errorInfo();
                $errInfo = $errInfo[2];
	       		$query->closeCursor();
				throw new QueryUpdateFirmaException("UPDATE - Failed updating firma with id: " . $this->id_firma . $errInfo);
			}
			
		    if ($query->rowCount() == 0) {		    	
		    	$this->version--;
		    	$query->closeCursor();
	       		throw new QueryWrongVersionException("Failed updating firma. Reason: wrong version!");
		    }
			
			$query->closeCursor();

		    $adresa_ok = $this->adresa->queryUpdateAddress($db);
		    
		    // TODO: De controlat pt fiecare contact daca nu cumva e folosit in cazul in care s-ar dori stergerea... 
		    // folosind functia Contact::isInUse($db, $contactId)
  		  		  		  		
  			//update la conturi in functie de statusul fiecarui cont  	
  			for ($i = 0; $i < count($this->conturi); $i++) {  			
  				if ($this->conturi[$i]->status == CT_CONT_MODIFIED) 
  					$this->conturi[$i]->queryUpdate($db);
  				  			
	  			if ($this->conturi[$i]->status == CT_CONT_NEW) 
	  				$this->conturi[$i]->queryInsertCont($db);
	  			
  				if ($this->conturi[$i]->status == CT_CONT_DELETED) 
  					$this->conturi[$i]->queryDeleteCont($db);  			
  			}
  			//end update la conturi in functie de statusul fiecarui cont
  			 
  			//update la contacte in functie de statusul fiecarui contact
  			for ($i = 0; $i < count($this->contacte); $i++) {  		
  				
  				if ($this->contacte[$i]->status == CT_CONTACT_MODIFIED) 
  					$this->contacte[$i]->queryUpdateContact($db);  				
  				  			
	  			if ($this->contacte[$i]->status == CT_CONTACT_NEW) 
	  				$this->contacte[$i]->queryInsertContact($db);
	  			
  				if ($this->contacte[$i]->status == CT_CONTACT_DELETED) 
  					$this->contacte[$i]->queryDeleteContact($db);  			
  			}
  			//end update la contacte in functie de statusul fiecarui contact
  			
  			//update la rute in functie de statusul fiecarei rute
  			for ($i = 0; $i < count($this->rute); $i++) {  		

  				if ($this->rute[$i]->status == CT_RUTA_FIRMA_MODIFIED) 
  					$this->rute[$i]->queryUpdateRutaFirma($db);  				
  				  			
	  			if ($this->rute[$i]->status == CT_RUTA_FIRMA_NEW) 
	  				$this->rute[$i]->queryInsertRutaFirma($db);
	  			
  				if ($this->rute[$i]->status == CT_RUTA_FIRMA_DELETED) 
  					$this->rute[$i]->queryDeleteRutaFirma($db);  			
  			}
  			//end update la rute in functie de statusul fiecarei rute
  			  			
  			$db->commit();		    
		}
		catch (QueryUpdateFirmaException $e) {
			$db->rollBack();		//maybe NOT needed ????
			$query->closeCursor();
        	throw new QueryUpdateFirmaException("UPDATE - Failed updating firma with id: " . $this->id_firma . $errInfo);
		}
		catch (QueryWrongVersionException $e) {
			$db->rollBack();		
			$query->closeCursor();
			
        	throw new QueryUpdateFirmaException("WRONG VERSION - Failed updating firma with id: " . $this->id_firma . $errInfo);
		}
		catch (QueryUpdateAddressException $e) {
			$db->rollBack();		
			$query->closeCursor();
        	throw new QueryUpdateFirmaException("ADDRESS - Failed updating firma with id: " . $this->id_firma . $errInfo);
		}		
		catch (QueryUpdateContException $e) {
			$db->rollBack();		
			$query->closeCursor();
			
        	throw new QueryUpdateFirmaException("UPDATE CONT - Failed updating firma with id: " . $this->id_firma . $errInfo);
		}
		catch (QueryInsertContException $e) {
			$db->rollBack();	
			$query->closeCursor();	
        	throw new QueryUpdateFirmaException("INSERT CONT - Failed updating firma with id: " . $this->id_firma . $errInfo);
		}
		catch (QueryDeleteContException $e) {
			$db->rollBack();	
			$query->closeCursor();	
        	throw new QueryUpdateFirmaException("DELETE CONT - Failed updating firma with id: " . $this->id_firma . $errInfo);
		}
		catch (QueryUpdateContactException $e) {
			$db->rollBack();		
			$query->closeCursor();
        	throw new QueryUpdateFirmaException("UPDATE CONTACT - Failed updating firma with id: " . $this->id_firma . $errInfo);
		}
		catch (QueryInsertContactException $e) {
			$db->rollBack();	
			$query->closeCursor();	
        	throw new QueryUpdateFirmaException("INSERT CONTACT- Failed updating firma with id: " . $this->id_firma . $errInfo);
		}
		catch (QueryDeleteRutaFirmaException $e) {
			$db->rollBack();	
			$query->closeCursor();	
        	throw new QueryUpdateFirmaException("DELETE Ruta - Failed updating firma with id: " . $this->id_firma . $errInfo);
		}
	    catch (QueryUpdateRutaFirmaException $e) {
			$db->rollBack();	
			$query->closeCursor();	
        	throw new QueryUpdateFirmaException("UPDATE Ruta - Failed updating firma with id: " . $this->id_firma . $errInfo);
		}
	    catch (QueryInsertRutaFirmaException $e) {
			$db->rollBack();	
			$query->closeCursor();	
        	throw new QueryUpdateFirmaException("INSERT Ruta - Failed updating firma with id: " . $this->id_firma . $errInfo);
		}	    	 
        return CT_RESULT_OK;
	}
	
	//trebuie rescrisa in loc de query-uri sa chemama metodele corespunzatoare
	public static function queryDeleteById($db, $id_firma, $id_client) {	
	           
		$query = $db->prepare("DELETE FROM firme WHERE id = :id_firma AND id_client = :id_client");
		$query->bindParam(':id_firma', $id_firma);	
		$query->bindParam(':id_client', $id_client);

		try {
			$db->beginTransaction();
			
			if ($query->execute() === FALSE) {	
                $errInfo = $query->errorInfo();
                $errInfo = $errInfo[2];		
	       		$query->closeCursor();	
				throw new QueryDeleteFirmaException("Failed deleting firma with id: " . $id_firma . $errInfo);
			}
			$query->closeCursor();
	       	
			Address::deleteAddressByIdOwner($db, $id_firma, CT_ADRESA_FIRMA);	

			Cont::deleteContByIdOwner($db, $id_firma, CT_CONT_FIRMA);
	       	
			Contact::deleteContactByIdFirma($db, $id_firma);
			
			RutaFirma::deleteRutaFirmaByIdFirma($db, $id_firma);
			
	       	$db->commit();
		    return CT_RESULT_OK;
		}
		catch (QueryDeleteFirmaException $e) {
			$db->rollBack();		
        	throw new QueryDeleteFirmaException("Failed deleting firma with id: " . $id_firma . $errInfo);
		}		
		catch (QueryDeleteAddressException $e) {
			$db->rollBack();		
        	throw new QueryDeleteFirmaException("Failed deleting firma with id: " . $id_firma . $errInfo);
		}		
		catch (QueryDeleteContactException $e) {
			$db->rollBack();		
        	throw new QueryDeleteFirmaException("Failed deleting firma with id: " . $id_firma . $errInfo);
		}
		catch (QueryDeleteRutaFirmaException $e) {
			$db->rollBack();		
        	throw new QueryDeleteFirmaException("Failed deleting firma with id: " . $id_firma . $errInfo);
		}		

      	return CT_RESULT_OK;    	  	      	
	}
	
	public static function queryLoadById($db, $id_firma, $id_client) {
		//id_client pentru securitate sa nu se dea in URL al id si sa vezi conturile de la alta firma
		$query = $db->prepare("SELECT *
                    				FROM firme
                    				WHERE id = :id_firma
                      					AND id_client = :id_client");
		$query->bindParam(':id_firma', $id_firma);	
		$query->bindParam(':id_client', $id_client);	

		try {						
			$db->beginTransaction();
			if ($query->execute() === FALSE) {             	
                $errInfo = $query->errorInfo();
                $errInfo = $errInfo[2];
				$query->closeCursor();	
				throw new QueryLoadFirmaException("Failed loading firma with id: " . $id_firma . $errInfo);
			}
			else $errInfo = null;
			
            $data = $query->fetch(PDO::FETCH_ASSOC);
            
            if (!isset($data['id'])) {
        		$query->closeCursor();
        		throw new QueryLoadFirmaException("Failed loading firma with id: " . $id_firma . " reason: id not existing");                    	        		                 	
        	}
                	
	        $firma = new Firma($data['id_client'], $data['nume'], $data['cf']
	                            , $data['rc'], $data['tel_fix'], $data['tel_fax'], $data['tel_mobil'], $data['email'], $data['web'], $data['tip']);
	        $firma->id_firma = (int) $data['id'];
	        $firma->version = $data['version'];        	
			$firma->comentariu = $data['comentariu'];
			$firma->calitate_firma = $data['calitate_firma'];
			
	        $query->closeCursor();     
	        
	        //incarcam adresele  
        	$firma->adresa = Address::queryLoadByFirma($db, $firma->id_firma);
        
        	//incarcam conturile
        	$firma->conturi = Cont::queryLoadContByOwner($db, CT_CONT_FIRMA, $id_firma);
        	$firma->contacte = Contact::queryLoadByFirma($db, $id_firma);
        	$firma->rute = RutaFirma::queryLoadByFirma($db, $id_firma);
        	$db->commit();
        	return $firma;	        
		}
		catch (QueryLoadFirmaException $e) {			
			$db->rollBack();	
			throw new QueryLoadFirmaException("FIRMA - Failed loading firma with id: " . $id_firma . $errInfo);
		}
		catch (QueryLoadAddressException $e) {
			$db->rollBack();	
			throw new QueryLoadFirmaException("ADDRESS - Failed loading firma with id: " . $id_firma . $errInfo);
		}
		catch (QueryLoadContException $e) {
			$db->rollBack();	
			throw new QueryLoadFirmaException("CONT - Failed loading firma with id: " . $id_firma . $errInfo);
		}		
		catch (QueryLoadContactException $e) {
			$db->rollBack();	
			throw new QueryLoadFirmaException("CONTACT - Failed loading firma with id: " . $id_firma . $errInfo);
		}
		catch (QueryLoadRutaFirmaException $e) {
			$db->rollBack();	
			throw new QueryLoadFirmaException("RUTE - Failed loading rute for firma with id: " . $id_firma . $errInfo);
		}		
	}
	
	public static function queryLoadByClient($db, $id_client) {
		$query = $db->prepare("SELECT *
                    			FROM firme
                    			WHERE id_client = :id_client");
		$query->bindParam(':id_client', $id_client);	
		
		if ($query->execute() === FALSE) {
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
        	$query->closeCursor();
			throw new QueryLoadFirmaException("Failed loading firma with id: " . $id_firma . $errInfo);
		}
		       
        $firme = array();
        
        while ($data = $query->fetch(PDO::FETCH_ASSOC)) {
	        $firma = new Firma($data['id_client'], $data['nume'], $data['cf']
	                            , $data['rc'], $data['tel_fix'], $data['tel_fax'], $data['tel_mobil'], $data['email'], $data['web'], $data['tip']);
	        $firma->id_firma = (int) $data['id'];
	        $firma->version = $data['version'];	
	        $firma->comentariu = $data['comentariu'];
			$firma->calitate_firma = $data['calitate_firma'];
				        
	        $firme[] = $firma;
        }

        $query->closeCursor();
        return $firme;
	}
	
	public static function queryLoadByClientWithName($db, $id_client = null) { /// cred ca aici nu trebuie pus id_client = null
		
		//daca $id_client e null se vor incarca toate firmele
		//daca nu atunci se vor incarca doar cele specificate
		
		if (isset($id_client) && !empty($id_client)) {
			$query = $db->prepare("SELECT id, nume, calitate_firma
	                    				FROM firme
	                    				WHERE id_client = :id_client");
		}
		else {
			$query = $db->prepare("SELECT id, nume FROM firme");			
		}
		$query->bindParam(":id_client", $id_client);
					
		if ($query->execute() === FALSE) {
            $errInfo = $query->errorInfo();
            $errInfo = $errInfo[2];
			$query->closeCursor();
           	throw new QueryLoadFirmaException("Failed loading firma for client with id: " . $id_client . $errInfo);
		}         
		   
        $firme = array();
        while ($data = $query->fetch(PDO::FETCH_ASSOC)) {            
            $firma = new Firma(null, $data['nume']);
	        $firma->id_firma = (int) $data['id'];
	        $firma->comentariu = $data['comentariu'];
			$firma->calitate_firma = $data['calitate_firma'];
				        
	        $firme[] = $firma;
        }
        
        $query->closeCursor();
        return $firme;
	}	
	
	public static function queryLoadByClientWithPageAndLimitAndCondition($db, $id_client, $page, $per_page, $conditie, $camp = null, $order = null, $keyword, $camp_order, $val1 = null, $val2 = null) {		

		$query = "SELECT SQL_CALC_FOUND_ROWS firme.id, firme.id_client, firme.nume, firme.cf, firme.rc, firme.tel_fix, 
					firme.tel_fax, firme.tel_mobil, firme.email, firme.web, firme.tip, firme.calitate_firma,
					adresa.id AS adresaid
	                    FROM firme ";
		if ($camp == '1rute') {
			$condition_val = "";
			$query .= " LEFT JOIN rute_firme ON rute_firme.firma_id = firme.id";
			if (!empty($val1) && !empty($val2)) {
				$condition_val .= " AND ((rute_firme.loc1 LIKE '%$val1%' AND rute_firme.loc2 LIKE '%$val2%') OR ";
				$condition_val .= "(rute_firme.loc1 LIKE '%$val2%' AND rute_firme.loc2 LIKE '%$val1%'))";
			}
			if (empty($val1))
				$condition_val .= " AND (rute_firme.loc1 LIKE '%$val2%' OR rute_firme.loc2 LIKE '%$val2%')";
			if (empty($val2))
				$condition_val .= " AND (rute_firme.loc1 LIKE '%$val1%' OR rute_firme.loc2 LIKE '%$val1%')";				
		}
					
		$query .= " LEFT JOIN adresa ON firme.id = adresa.id_owner
	                    				WHERE adresa.tip = " . CT_ADRESA_FIRMA . 
										$condition_val . ' AND ' . stripcslashes($conditie);
		$coloane_firme = explode(',', $_SESSION['user_logat']->coloane_firme);
		//in caz ca coloana dupa care s-a sortat a fost scoala atunci punem implicit dupa nume pentru ca tot timpul numele
		//este afisat implicit
		
		if (!in_array($camp_order, $coloane_firme)) $camp_order = 'nume';
		
		if (!isset($camp_order)) {
		     $query .= " ORDER BY nume DESC";
		}		
		
		else if ($camp_order != -1) $query .= " ORDER BY $camp_order $order";
        else if ($camp_order == -1) $query .= " ORDER BY nume $order";
	    $query .= " LIMIT ". ($page * $per_page) . ", $per_page";		
//		echo $query;
//		die();
		if (($result = $db->query($query)) === FALSE) {						
            $errInfo = $db->errorInfo();
            $errInfo = $errInfo[2];
           	throw new QueryLoadFirmaException("Failed loading firma for client with id: " . $id_client . $errInfo);
		}
		
        $query = "SELECT FOUND_ROWS() AS total";

        if (($result2 = $db->query($query)) === FALSE) {        	
            $errInfo = $db->errorInfo();
            $errInfo = $errInfo[2];
           	throw new QueryLoadFirmaException("Failed loading firme for client with id: " . $id_client . $errInfo);
		}         
		
        $data2 = $result2->fetch(PDO::FETCH_ASSOC);
        $total = $data2['total'];
		$firme = array();
        $adrese = array();
        
		while ($data = $result->fetch(PDO::FETCH_ASSOC)) {            
            $firma = new Firma($id_client, $data['nume'], $data['cf'], $data['rc'], $data['tel_fix'], $data['tel_fax'], $data['tel_mobil'], $data['email'], $data['web'], $data['tip']);
	        $firma->id_firma = (int) $data['id'];
	        $firma->comentariu = $data['comentariu'];
			$firma->calitate_firma = $data['calitate_firma'];
				        
	        $firme[] = $firma;
	        $adresa = Address::queryLoadAddress($db, $data['adresaid']);
	        $adrese[] = $adresa;
        }
        
        $arr = array();
        $arr['firme'] = $firme;
        $arr['adrese'] = $adrese;        
        $arr['total'] = $total;
        return $arr;
	}
	
	//get last $limit firms from database
	
	public static function getLast($db, $id_client, $limit) {
				
		$query = "SELECT * FROM firme
	                   WHERE id_client = $id_client
					   ORDER by id DESC
					   LIMIT $limit;";	

		if (($result = $db->query($query)) === FALSE) {					
            $errInfo = $db->errorInfo();
            $errInfo = $errInfo[2];	
           	throw new QueryLoadFirmaException("Failed loading last $limit firms for client with id: " . $id_client . $errInfo);
		}
		
		$firme = array();
        
		while ($data = $result->fetch(PDO::FETCH_ASSOC)) {            
            $firma = new Firma($id_client, $data['nume'], $data['cf'], $data['rc'], $data['tel_fix'], $data['tel_fax'], $data['tel_mobil'], $data['email'], $data['web'], $data['tip']);
	        $firma->id_firma = (int) $data['id'];
	        $firma->comentariu = $data['comentariu'];
			$firma->calitate_firma = $data['calitate_firma'];
				        
	        $firme[] = $firma;
        }
        
        return $firme;
	}	
	
	public static function getIdLastFirm($db, $id_client) {
		$query = "SELECT id FROM firme
	                   WHERE id_client = $id_client
					   ORDER by id DESC
					   LIMIT 1;";	

		if (($result = $db->query($query)) === FALSE) {					
            $errInfo = $db->errorInfo();
            $errInfo = $errInfo[2];	
           	throw new QueryLoadFirmaException("Failed loading last 1 firm for client with id: " . $id_client . $errInfo);
		}
		
		$data = $result->fetch(PDO::FETCH_ASSOC);        
        return $data['id'];		
	}
	
	public static function queryLighUpdate($db, $id_client, $id_firma, $nume_firma, $tel_fix, $tel_fax, $tel_mobil, $email) {
		$query = "UPDATE firme
						SET nume = '$nume_firma', tel_fix = '$tel_fix', tel_fax = '$tel_fax', tel_mobil = '$tel_mobil',
						email = '$email'
	                    WHERE id_client = $id_client
	                   	AND id = $id_firma";

		if (($result = $db->query($query)) === FALSE) {					
            $errInfo = $db->errorInfo();
            $errInfo = $errInfo[2];	
           	throw new QueryUpdateFirmaException("Failed updating firm with id: " . $id_firma . $errInfo);
		}		
	}
}

?>